<template>
  <div class="new-folder-container">
    <div class="page-header">
      <div class="header-content">
        <div class="header-icon">
          <el-icon><FolderAdd /></el-icon>
        </div>
        <div class="header-text">
          <h2>新建文件夹</h2>
          <p>创建一个新的文件夹来组织您的文件</p>
        </div>
      </div>
    </div>

    <div class="form-container">
      <el-card class="form-card">
        <el-form :model="formData" :rules="rules" ref="formRef" label-width="100px">
          <el-form-item label="文件夹名称" prop="folderName">
            <el-input
              v-model="formData.folderName"
              placeholder="请输入文件夹名称"
              maxlength="50"
              show-word-limit
              clearable
              size="large"
            >
              <template #prefix>
                <el-icon><Folder /></el-icon>
              </template>
            </el-input>
          </el-form-item>

          <el-form-item label="描述" prop="description">
            <el-input
              v-model="formData.description"
              type="textarea"
              placeholder="请输入文件夹描述（可选）"
              :rows="3"
              maxlength="200"
              show-word-limit
            />
          </el-form-item>

          <el-form-item>
            <div class="button-group">
              <el-button size="large" @click="resetForm">
                <el-icon><RefreshLeft /></el-icon>
                重置
              </el-button>
              <el-button
                type="primary"
                size="large"
                @click="createFolder"
                :loading="loading"
              >
                <el-icon><Plus /></el-icon>
                创建文件夹
              </el-button>
            </div>
          </el-form-item>
        </el-form>
      </el-card>
    </div>

    <!-- 最近创建的文件夹 -->
    <div class="recent-folders" v-if="recentFolders.length > 0">
      <el-card>
        <template #header>
          <div class="section-header">
            <h3>最近创建的文件夹</h3>
            <el-button type="text" @click="$router.push('/userfolders')">
              查看全部
            </el-button>
          </div>
        </template>

        <div class="folder-grid">
          <div
            v-for="folder in recentFolders"
            :key="folder.id"
            class="folder-item"
            @click="openFolder(folder)"
          >
            <div class="folder-icon">
              <el-icon><Folder /></el-icon>
            </div>
            <div class="folder-info">
              <div class="folder-name">{{ folder.folder_name }}</div>
              <div class="folder-date">{{ formatDate(folder.created_at) }}</div>
            </div>
          </div>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { ElMessage } from "element-plus";
import { useRouter } from "vue-router";
import {
  FolderAdd,
  Folder,
  Plus,
  RefreshLeft
} from "@element-plus/icons-vue";
import { addFolderApi, getFolderApi } from "@/utils/api";

const router = useRouter();
const formRef = ref();
const loading = ref(false);

const formData = ref({
  folderName: "",
  description: ""
});

const recentFolders = ref([]);

const rules = {
  folderName: [
    { required: true, message: "请输入文件夹名称", trigger: "blur" },
    { min: 1, max: 50, message: "文件夹名称长度在 1 到 50 个字符", trigger: "blur" },
    {
      pattern: /^[^<>:"/\\|?*]+$/,
      message: "文件夹名称不能包含特殊字符 < > : \" / \\ | ? *",
      trigger: "blur"
    }
  ]
};

// 获取当前时间
const getCurrentTime = () => {
  const date = new Date();
  return date.toISOString().slice(0, 19).replace('T', ' ');
};

// 创建文件夹
const createFolder = async () => {
  if (!formRef.value) return;

  try {
    const valid = await formRef.value.validate();
    if (!valid) return;

    loading.value = true;

    const params = {
      user_id: localStorage.getItem("id"),
      folder_name: formData.value.folderName,
      created_at: getCurrentTime()
    };

    const response = await addFolderApi(params);

    if (response.code === 200) {
      ElMessage.success("文件夹创建成功！");
      resetForm();
      loadRecentFolders(); // 刷新最近文件夹列表

      // 可选：跳转到文件夹管理页面
      setTimeout(() => {
        router.push("/userfolders");
      }, 1500);
    } else {
      ElMessage.error(response.msg || "创建失败，请重试");
    }
  } catch (error) {
    console.error("创建文件夹失败:", error);
    ElMessage.error("创建失败，请重试");
  } finally {
    loading.value = false;
  }
};

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields();
  }
  formData.value = {
    folderName: "",
    description: ""
  };
};

// 加载最近创建的文件夹
const loadRecentFolders = async () => {
  try {
    const id = localStorage.getItem("id");
    const response = await getFolderApi({ id });

    if (response.code === 200) {
      // 获取最近的5个文件夹
      recentFolders.value = response.data.data
        .sort((a, b) => new Date(b.created_at) - new Date(a.created_at))
        .slice(0, 5);
    }
  } catch (error) {
    console.error("加载最近文件夹失败:", error);
  }
};

// 打开文件夹
const openFolder = (folder) => {
  router.push(`/details/${folder.id}`);
};

// 格式化日期
const formatDate = (dateString) => {
  return new Date(dateString).toLocaleDateString('zh-CN');
};

onMounted(() => {
  loadRecentFolders();
});
</script>

<style lang="less" scoped>
.new-folder-container {
  padding: 20px;
  max-width: 800px;
  margin: 0 auto;
}

.page-header {
  margin-bottom: 30px;

  .header-content {
    display: flex;
    align-items: center;
    gap: 16px;

    .header-icon {
      width: 60px;
      height: 60px;
      background: linear-gradient(135deg, #409eff, #67c23a);
      border-radius: 12px;
      display: flex;
      align-items: center;
      justify-content: center;
      color: white;
      font-size: 24px;
    }

    .header-text {
      h2 {
        margin: 0 0 8px 0;
        color: #303133;
        font-size: 24px;
        font-weight: 600;
      }

      p {
        margin: 0;
        color: #606266;
        font-size: 14px;
      }
    }
  }
}

.form-container {
  margin-bottom: 30px;

  .form-card {
    border-radius: 12px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);

    .el-form {
      padding: 20px;
    }

    .button-group {
      display: flex;
      gap: 12px;
      justify-content: flex-end;

      .el-button {
        min-width: 120px;
      }
    }
  }
}

.recent-folders {
  .section-header {
    display: flex;
    justify-content: space-between;
    align-items: center;

    h3 {
      margin: 0;
      color: #303133;
      font-size: 16px;
      font-weight: 600;
    }
  }

  .folder-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
    gap: 16px;
    margin-top: 16px;

    .folder-item {
      display: flex;
      align-items: center;
      padding: 16px;
      border: 1px solid #ebeef5;
      border-radius: 8px;
      cursor: pointer;
      transition: all 0.3s;

      &:hover {
        border-color: #409eff;
        box-shadow: 0 2px 8px rgba(64, 158, 255, 0.2);
        transform: translateY(-2px);
      }

      .folder-icon {
        width: 40px;
        height: 40px;
        background: #f0f9ff;
        border-radius: 8px;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-right: 12px;
        color: #409eff;
        font-size: 20px;
      }

      .folder-info {
        flex: 1;
        min-width: 0;

        .folder-name {
          font-weight: 500;
          color: #303133;
          margin-bottom: 4px;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }

        .folder-date {
          font-size: 12px;
          color: #909399;
        }
      }
    }
  }
}

@media (max-width: 768px) {
  .new-folder-container {
    padding: 15px;
  }

  .page-header .header-content {
    flex-direction: column;
    text-align: center;
    gap: 12px;
  }

  .form-container .form-card .el-form {
    padding: 15px;
  }

  .folder-grid {
    grid-template-columns: 1fr;
  }

  .button-group {
    flex-direction: column;

    .el-button {
      width: 100%;
    }
  }
}
</style>
